import React, { useState } from 'react';
import { Tree } from 'antd';
const initTreeDate = [
    {
        title: 'Expand to load',
        key: '0',
    },
    {
        title: 'Expand to load',
        key: '1',
    },
    {
        title: 'Tree Node',
        key: '2',
        isLeaf: true,
    },
]; // It's just a simple demo. You can use tree map to optimize update perf.

function updateTreeData(list, key, children) {
    console.log('1111', list, key, children);
    return list.map((node) => {
        if (node.key === key) {
            return { ...node, children };
        } else if (node.children) {
            return { ...node, children: updateTreeData(node.children, key, children) };
        }
        return node;
    });
}

export default () => {
    const [ count, setCount ] = useState(0);
    const [treeData, setTreeData] = useState(initTreeDate);

    function onLoadData({ key, children }) {
        return new Promise((resolve) => {
            if (children) {
                resolve();
                return;
            }

            //   setTimeout(() => {
            //     setTreeData((origin) =>
            //       updateTreeData(origin, key, [
            //         {
            //           title: 'Child Node',
            //           key: `${key}-0`,
            //         },
            //         {
            //           title: 'Child Node',
            //           key: `${key}-1`,
            //         },
            //       ]),
            //     );
            //     resolve();
            //   }, 1000);
            window.axios.get("/form/tree").then(
                res => {
                    const result = res.data.map(item => {
                        return {
                            title: item.title,
                            key: `${key}-${item.key}`,
                            isLeaf: item.type === "car"
                        }
                    })
                    setTreeData((origin) => updateTreeData(origin, key, result))
                }
            )
            resolve();
        });
    }

    return (
        <>
            <Tree loadData={onLoadData} treeData={treeData} />
        </>
    )

};